const express = require('express');
const router = express.Router();
const db = require('../../../MySql');
const { formatDateTime } = require('../../utils/dateUtils');

router.post('/user/exam/my-paging', async (req, res) => {
    try {
        const userId = req.body.params.userId
        const {size,current}=req.body

        // 查询用户考试记录，关联考试标题
        const sql = `
        SELECT 
            ue.*, 
            e.title as title,
            su.real_name as realName
        FROM el_user_exam ue
        JOIN el_exam e ON ue.exam_id = e.id
        JOIN sys_user su ON ue.user_id = su.id
        WHERE ue.user_id = ?
        ORDER BY ue.create_time DESC
    `;

        const [results] = await db.query(sql, [userId])
        if (results.length === 0) {
            return res.json({
                msg: "用户未参加任何考试",
                code: 0,
                data: {
                    records: [],
                    total: 0,
                    size: size, // 默认分页大小
                    current: current, // 默认当前页
                    orders: [],
                    optimizeCountSql: true,
                    hitCount: false,
                    searchCount: true,
                    pages: 0
                },
                success: true
            })
        }

        const records = results.map(item => ({
            id: item.id,
            userId: item.user_id,
            examId: item.exam_id,
            tryCount: item.try_count,
            maxScore: item.max_score,
            passed: item.passed === 1,
            createTime: formatDateTime(item.create_time),
            updateTime: formatDateTime(item.update_time),
            title: item.title,
            realName: item.realName
        }))

        return res.json({
            msg: "操作成功！",
            code: 0,
            data: {
                records: records,
                total: records.length,
                size: size, // 默认分页大小
                current: current, // 默认当前页
                orders: [],
                optimizeCountSql: true,
                hitCount: false,
                searchCount: true,
                pages: Math.ceil(records.length / 10) // 计算总页数
            },
            success: true
        })
    } catch (error) {
        console.error("数据库查询失败:", error);
        return res.json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        });
    }
})


router.post('/user/exam/paging', async (req, res) => {
    try {
        const { examId, realName } = req.body.params
        const { size, current } = req.body

        // 构建基础SQL查询
        let sql = `
        SELECT 
            ue.*, 
            e.title as title,
            su.real_name as realName
        FROM el_user_exam ue
        JOIN el_exam e ON ue.exam_id = e.id
        JOIN sys_user su ON ue.user_id = su.id
        WHERE ue.exam_id = ?`;

        const queryParams = [examId];
        const countParams = [examId];

        // 添加姓名筛选条件
        if (realName && realName.trim()) {
            sql += ` AND su.real_name LIKE ?`;
            countSql += ` AND su.real_name LIKE ?`;
            queryParams.push(`%${realName}%`);
            countParams.push(`%${realName}%`);
        }

        // 执行查询
        const [results] = await db.query(sql, queryParams)

        // 格式化返回数据
        const records = results.map(item => ({
            id: item.id,
            userId: item.user_id,
            examId: item.exam_id,
            tryCount: item.try_count,
            maxScore: item.max_score,
            passed: item.passed === 1,
            createTime: formatDateTime(item.create_time),
            updateTime: formatDateTime(item.update_time),
            title: item.title,
            realName: item.realName
        }));

        return res.json({
            msg: "操作成功！",
            code: 0,
            data: {
                records: records,
                total: records.length,
                size: size,
                current: current,
                orders: [],
                optimizeCountSql: true,
                hitCount: false,
                searchCount: true,
                pages: Math.ceil(records.length / size)
            },
            success: true
        });
    } catch (error) {
        console.error('分页查询错误:', error);
        return res.status(500).json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        });
    }
});


module.exports = router;